package com.edgclub.edg.task;

import android.content.Context;
import android.os.Looper;
import android.util.Log;

import com.android.volley.VolleyError;
import com.edgclub.edg.Constant;
import com.edgclub.edg.api.ResultCode;
import com.edgclub.edg.api.TopicApi;
import com.edgclub.edg.api.UploadApi;
import com.edgclub.edg.api.param.PostsParam;
import com.edgclub.edg.http.VolleyListener;
import com.edgclub.edg.http.async.AsyncHttpResponseHandler;
import com.edgclub.edg.utils.util.BitmapUtility;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.dao.DaoHelper;
import com.hyphenate.easeui.dao.ReplyImageDao;
import com.hyphenate.easeui.model.ReplyImageInfo;

import java.io.File;
import java.util.ArrayList;

import cz.msebera.android.httpclient.Header;

/**
 * 发送回复图片的服务
 */
public class GzReplyImageUploadThread  {

    private Context mContext;

    private TopicApi topicApi;
    private UploadApi uploadApi;

    public GzReplyImageUploadThread(Context mContext) {
        super();
        this.mContext = mContext;
        uploadApi = new UploadApi(mContext);
        topicApi = new TopicApi(mContext);
        new Thread(new Runnable() {
            @Override
            public void run() {
                upload();
            }
        }).start();
    }


    protected Void upload() {

        ArrayList<ReplyImageInfo> infos = (ArrayList<ReplyImageInfo>) DaoHelper.getInstance(mContext,EaseConstant.DB_NAME_REPLY_IMAGE).loadAllT();

        if (infos != null && infos.size() > 0) {
            Log.i("infos", "-------------"+infos.size());
            Looper.prepare();
            for (int i = 0; i < infos.size(); i++) {
                ReplyImageInfo info = infos.get(i);
                if(info.getUploadstate().equals("false")){
                    try {
                        String pic0 = info.getPath();
                        String userImageFileName = Constant.TOPICIMAGEPATH
                                + pic0.hashCode();
                        if (pic0.endsWith("png")&&info.getIsOri().equals("false")) {
                            BitmapUtility.compressPNGFromBitmap(pic0, userImageFileName,300);
                        } else if ((pic0.endsWith("jpg") || pic0.endsWith("jpeg"))&&info.getIsOri().equals("false")) {
                            BitmapUtility.compressImage(pic0, userImageFileName);
                        } else {
                                userImageFileName = pic0;
                        }
                        uploadApi.beginUploadReplyAlbum(new File(
                                        userImageFileName), info.getTopicId(),info.getReplyId(), String.valueOf(i), info.getIsOri(),
                                new UploadImageHandler(info));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            Looper.loop();
        }
        return null;

    }

    /**
     * 上传相册回调
     */
    class UploadImageHandler extends AsyncHttpResponseHandler {

        private ReplyImageInfo info;

        public UploadImageHandler(ReplyImageInfo info) {
            this.info = info;
        }

        @Override
        public void onStart() {

        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            try {
                String recString=new String(responseBody ,"UTF-8");
                Log.d("recString",recString);
                if (JSONHelper.isSuccess(recString)) {
                    String pic1 = info.getPath();
                    String userImageFileName = Constant.TOPICIMAGEPATH
                            + pic1.hashCode();
                    File file = new File(userImageFileName);
                    if (file.exists()) {
                        file.delete();
                    }
                    info.setUploadstate("true");
                    DaoHelper.getInstance(mContext,EaseConstant.DB_NAME_REPLY_IMAGE).update(info);
                    if(!DaoHelper.getInstance(mContext,EaseConstant.DB_NAME_REPLY_IMAGE)
                            .isHas(ReplyImageDao.Properties.replyId,info.getReplyId(),
                                    ReplyImageDao.Properties.uploadstate,"false")){
                        topicImageFinish(info);
                    }
                }else{
                    Log.d("error:",recString+"---------------");
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            try {
                String recString=new String(responseBody ,"UTF-8");
                Log.d("error",error.toString()+"--------------"+recString);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    private void topicImageFinish(ReplyImageInfo info) {
        PostsParam postsParam = new PostsParam();
        postsParam.setUserId(new UserPrefUtils(mContext).getUser().getId());
        postsParam.setPostsId(info.getTopicId());
        postsParam.setReplyId(info.getReplyId());
        topicApi.replyimageFinish(postsParam, new FinishPosts(info));
    }

    /**
     * 发布贴子的监听
     */
    class FinishPosts implements VolleyListener {

        private ReplyImageInfo info;


        public FinishPosts(ReplyImageInfo info) {
            super();
            this.info = info;
        }

        @Override
        public void onStart(String tag) {

        }

        @Override
        public void onSuccess(String response,String tag) {
            if (JSONHelper.isSuccess(response)) {
                DaoHelper.getInstance(mContext,EaseConstant.DB_NAME_REPLY_IMAGE).deleteById(ReplyImageDao.Properties.replyId,info.getReplyId());
                Log.i("test", "model.deleteModel");
            } else {

            }
        }

        @Override
        public void onFaile(VolleyError volleyError,String tag) {
//            GuZhiApplication.getInstance().sendTopicImageNotification();
            ResultCode.toastVolleyError(mContext, volleyError);
        }

    }

}
